<template>
	<Card mode = "products">
		<div class = "controls">
			<el-button type = "success" :disabled = "!userStore.isAdmin" @click = "openAddDialog">新增产品</el-button>
		</div>
		<el-table height = "80vh" :data = "filterProducts" v-loading = "loading" row-key = "id">
			<el-table-column type = "selection" width = "55" />
			<el-table-column prop = "title" label = "标题" />
			<el-table-column prop = "procity" label = "产地" />
			<el-table-column prop = "price" label = "价格" />
			<el-table-column prop = "realSales" label = "真实销量" />
			<el-table-column prop = "picPath" label = "图片路径" />
			<el-table-column fixed = "right" label = "操作" min-width = "120">
				<template #header>
					<el-input v-model = "search" size = "small" placeholder = "键入关键字搜索" />
				</template>
				<template #default = "scope">
					<el-button :disabled = "!userStore.isAdmin" link type = "primary" size = "small" @click.prevent = "EditRow(scope.row)">
						编辑
					</el-button>
					<el-popconfirm title = "是否确认删除?" @confirm = "deleteRow(scope.row)">
						<template #reference>
							<el-button :disabled = "!userStore.isAdmin" link type = "danger" size = "small">
								删除
							</el-button>
						</template>
					</el-popconfirm>
				</template>
			</el-table-column>
		</el-table>
	</Card>

	<el-dialog v-model = "dialogFormVisible" title = "编辑产品信息" width = "500">
		<el-form
			ref = "ruleFormRef"
			:model = "editProduct">
			<el-form-item label = "标题" prop = "title">
				<el-input v-model = "editProduct.title" autocomplete = "off" />
			</el-form-item>
			<el-form-item label = "产地" prop = "procity">
				<el-input v-model = "editProduct.procity" autocomplete = "off" />
			</el-form-item>
			<el-form-item label = "价格" prop = "price">
				<el-input v-model = "editProduct.price" autocomplete = "off" />
			</el-form-item>
			<el-form-item label = "真实销量" prop = "realSales">
				<el-input v-model = "editProduct.realSales" autocomplete = "off" />
			</el-form-item>
			<el-form-item label = "图片路径" prop = "picPath">
				<el-input v-model = "editProduct.picPath" autocomplete = "off" />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class = "dialog-footer">
				<el-button @click = "closeEditDialog">取消</el-button>
				<el-button type = "primary" @click = "submitEdit(ruleFormRef)">
					{{ op === 'add' ? '添加' : '更新' }}
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang = "ts" setup>
import Api from '@/api'
import { computed, onMounted, reactive, ref } from 'vue'
import Card from '@/components/Card.vue'
import { showMessage } from '@/utils/messageUtils'
import simpleRequest from '@/utils/requestUtils'
import { FormInstance } from 'element-plus'
import useStore from '@/store'

//* Store
const { userStore } = useStore()

interface Product {
	id: string
	title: string
	procity: string
	price: number
	realSales: string
	picPath: string
}

//? 表单ref 不能绑定 需要直接 ref = 'ruleFormRef'
const ruleFormRef = ref<FormInstance>()

//* 商品列表
const products = ref<Product[]>([])

//* 数据是否加载中
const loading = ref(true)

//* 关键词查找
const search = ref('')
const filterProducts = computed(() => {
	return products.value.filter(data =>
		!search.value ||
		data.title.toLowerCase().includes(search.value.toLowerCase()) ||
		data.procity.toLowerCase().includes(search.value.toLowerCase()) ||
		data.price.toString().toLowerCase().includes(search.value.toLowerCase()) ||
		data.realSales.toLowerCase().includes(search.value.toLowerCase()) ||
		data.picPath.toLowerCase().includes(search.value.toLowerCase())
	)
})

//* 是否显示编辑对话框
const dialogFormVisible = ref(false)

//* 当前编辑的商品信息
const editProduct = reactive<{
	id: string
	title: string
	procity: string
	price: number
	realSales: string
	picPath: string
}>({
	id: null,
	title: '',
	procity: '',
	price: 0.00,
	realSales: '',
	picPath: ''
})

//* 编辑产品信息
const EditRow = (selectedProduct: Product) => {
	dialogFormVisible.value = true

	//* 没有必要去查询 数据存储在 products 中
	// simpleRequest(Api.getProductById, selectedProduct.id, data => {
	//   Object.assign(editProduct, data.data);
	// })
	Object.assign(editProduct, selectedProduct)
	op.value = 'update'
}

const op = ref<'add' | 'update'>('')

//* 添加商品
const openAddDialog = () => {
	resetForm()
	dialogFormVisible.value = true
	op.value = 'add'
}

//* 清空编辑框信息
const resetForm = () => {
	Object.assign(editProduct, {
		id: null,
		title: '',
		procity: '',
		price: 0.00,
		realSales: '',
		picPath: ''
	})
}

//* 关闭弹框
const closeEditDialog = () => {
	resetForm()
	dialogFormVisible.value = false
}

//* 是否正在提交
const isSubmitting = ref(false)

//* 提交更新
const submitEdit = (form) => {
	if (isSubmitting.value) return

	form?.validate(async (valid) => {
		if (!valid) {
			showMessage(op === 'add' ? '添加商品失败' : '更新商品信息失败', 'error')
			return
		}
		isSubmitting.value = true

		const formDataCopy = { ...editProduct }

		op.value === 'add'
			? simpleRequest(Api.createProduct, editProduct, _ => {
				products.value.push(formDataCopy)
			}, null, '添加商品失败')
			: simpleRequest(Api.updateProductById, editProduct, _ => {
				const currentIndex = products.value.findIndex(product => product.id === formDataCopy.id)
				if (~currentIndex) products.value[currentIndex] = { ...formDataCopy }
			}, null, '更新商品信息失败')

		isSubmitting.value = false

		closeEditDialog()
	})
}

//* 删除产品信息
const deleteRow = (selectedProduct: Product) => {
	simpleRequest(Api.deleteProductById, selectedProduct.id, _ => {
		products.value = products.value.filter(product => product.id !== selectedProduct.id)
	})
}

//* 挂载时获取产品列表
onMounted(() => {
	loading.value = true

	simpleRequest(Api.getAllProducts, null, data => {
		products.value = data.data.map((productData: any) => ({
			id: productData.id,
			title: productData.title,
			procity: productData.procity,
			price: productData.price.toFixed(2),
			realSales: productData.realSales,
			picPath: productData.picPath
		}))
	})

	loading.value = false
})
</script>

<style scoped>
.controls {
	position: fixed;
	top: 3vh;
	right: 5vw;
}
</style>